package cn.itcast.action.user;


import cn.itcast.action.common.BaseAction;
import cn.itcast.cache.BaseCacheService;
import cn.itcast.domain.user.UserModel;
import cn.itcast.service.user.IUserService;
import cn.itcast.service.userAccount.IUserAccountService;
import cn.itcast.utils.*;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Namespace("/user")
@Controller
@Scope("prototype")
public class UserAction extends BaseAction implements ModelDriven<UserModel> {

    private UserModel user = new UserModel();

    @Override
    public UserModel getModel() {
        return user;
    }


    @Autowired
    private BaseCacheService baseCacheService;

    @Autowired
    private IUserAccountService userAccountService;

    @Autowired
    private IUserService userService;




@Action("login")
public void login(){
    String signUuid=this.getRequest().getParameter("signUuid");
    String signCode=this.getRequest().getParameter("signCode");
    String _signCode=baseCacheService.get(signUuid);
    try {
        if(!_signCode.equalsIgnoreCase(signCode)){
            this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.INPUT_ERROR_OF_VALIDATE_CARD).toJSON());
            return;
        }

      String str=user.getUsername();
        if(CommomUtil.isMobile(str)){
      UserModel um=userService.findByPhone(str);
      str=um.getUsername();
        }


        String pwd=MD5Util.md5(str+user.getPassword().toLowerCase());

        UserModel  u=userService.login(str,pwd);
        if(u!=null){
       String token=generateUserToken(u.getUsername());
Map<String,Object> data=new HashMap<String, Object>();
data.put("id",u.getId());
data.put("userName",u.getUsername());

            this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.SUCCESS).setData(data).setToken(token).toJSON());
        }else {
            this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.ERROR_OF_USERNAME_PASSWORD).toJSON());
        }
    } catch (IOException e) {
        e.printStackTrace();

    }


}








    @Action("signup")
    public void regist() {
        String pwdMd5=MD5Util.md5(user.getUsername()+user.getPassword().toLowerCase());
        user.setPassword(pwdMd5);

     boolean  flag= userService.addUser(user);
        try {
            if(flag){
             userAccountService.add(user.getId());
                String token = generateUserToken(user.getUsername());

                Map<String,Object> map=new HashMap<String,Object>();
                map.put("id",user.getId());

                this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.SUCCESS).setData(map).setToken(token).toJSON());
                return;
            }else {
                this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.BREAK_DOWN).toJSON());
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Action("codeValidate")
    public void codeValidate() {
        String signUuid = this.getRequest().getParameter("signUuid");
        String signCode = this.getRequest().getParameter("signCode");
        String _signCode = baseCacheService.get(signUuid);
        try {

            if (StringUtils.isEmpty(signCode)) {
                this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.NULL_OF_VALIDATE_CARD).toJSON());
                return;
            }
            if (StringUtils.isEmpty(_signCode)) {
                this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.NULL_OF_VALIDATE_CARD).toJSON());
                return;
            }


            if (signCode.equalsIgnoreCase(_signCode)) {
                this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.SUCCESS).toJSON());
                return;
            } else {
                this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.INPUT_ERROR_OF_VALIDATE_CARD).toJSON());
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Action("validatePhone")
    public void validatePhone() {
        String phone = this.getRequest().getParameter("phone");
        UserModel user = userService.findByPhone(phone);
        try {
            if (user == null) {
                this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.SUCCESS).toJSON());
                return;
            } else {
                this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.MOBILE_ALREADY_REGISTER).toJSON());
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Action("validateUserName")
    public void validateUserName() {
        String username = this.getRequest().getParameter("username");
        UserModel user = userService.findByUsername(username);
        try {
            if (user == null) {
                this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.SUCCESS).toJSON());
                return;
            } else {
                this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.ALREADY_EXIST_OF_USERNAME).toJSON());
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Action("validateCode")
    public void validateCode() {
        String tokenUuid = this.getRequest().getParameter("tokenUuid");
        String uuid = baseCacheService.get(tokenUuid);
        try {
            if (StringUtils.isEmpty(uuid)) {
                this.getResponse().getWriter().write(Response.build().setStatus("-999").toJSON());
                return;
            }
            String str = ImageUtil.getRundomStr();
            baseCacheService.del(uuid);
            baseCacheService.set(tokenUuid, str);
            baseCacheService.expire(tokenUuid, 3 * 60);
            ImageUtil.getImage(str, this.getResponse().getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Action("uuid")
    public void uuid() {
        String uuid = UUID.randomUUID().toString();

        baseCacheService.set(uuid, uuid);
        baseCacheService.expire(uuid, 3 * 60);

        try {
            this.getResponse().getWriter().write(Response.build().setStatus("1").setUuid(uuid).toJSON());
        } catch (IOException e) {
            e.printStackTrace();
        }


    }



    public String generateUserToken(String userName) {

        try {
            // 生成令牌
            String token = TokenUtil.generateUserToken(userName);

            // 根据用户名获取用户
            UserModel user = userService.findByUsername(userName);
            // 将用户信息存储到map中。
            Map<String, Object> tokenMap = new HashMap<String, Object>();
            tokenMap.put("id", user.getId());
            tokenMap.put("userName", user.getUsername());
            tokenMap.put("phone", user.getPhone());
            tokenMap.put("userType", user.getUserType());
            tokenMap.put("payPwdStatus", user.getPayPwdStatus());
            tokenMap.put("emailStatus", user.getEmailStatus());
            tokenMap.put("realName", user.getRealName());
            tokenMap.put("identity", user.getIdentity());
            tokenMap.put("realNameStatus", user.getRealNameStatus());
            tokenMap.put("payPhoneStatus", user.getPhoneStatus());

            baseCacheService.del(token);
            baseCacheService.setHmap(token, tokenMap); // 将信息存储到redis中

            // 获取配置文件中用户的生命周期，如果没有，默认是30分钟
            String tokenValid = ConfigurableConstants.getProperty("token.validity", "30");
            tokenValid = tokenValid.trim();
            baseCacheService.expire(token, Long.valueOf(tokenValid) * 60);

            return token;
        } catch (Exception e) {
            e.printStackTrace();
            return Response.build().setStatus("-9999").toJSON();
        }
    }

    @Action("logout")
    public void logout(){
    String token=this.getRequest().getHeader("token");
        Map<String, Object> map = baseCacheService.getHmap(token);
        try {
            if(map==null||map.size()==0){
                this.getResponse().getWriter().write(Response.build().setStatus(FrontStatusConstants.NULL_TOKEN).toJSON());
                return;
            }
                baseCacheService.del(token);
            this.getResponse().getWriter().write(Response.build().setStatus("1").toJSON());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}

